#!/usr/bin/python
# encoding: utf-8
'''
@File    :   code.py
@Time    :   2020/03/11 21:54:19
@Author  :   fangkaijin 
@Version :   1.0
@Contact :   fangkaijin@gmail.com
@License :   杭州移动互联
@Desc    :   None
'''

# 导入库包

import sys, os
import tkinter as tk
import tkinter.ttk as ttk
import datetime
import time

from calendarutil import Calendar
from seachdata import seacheData
from showlog import ShowLog

logInfos = []

class SearchUI(object):
    def __init__(self):
        self.root = tk.Tk()
        self.logInfos = logInfos
        self._createUi_()

    def _createUi_(self):
        # 设置窗口标题:
        self.root.title('美术宝')
        self.root.geometry('1000x800+300+100')
        #显示顶部消息
        self._topmsg_()
        #查询参数
        self._seacherMeun_()
        #显示列表
        self._resultList_()
        #监听列表双击事件
        self._doItemClick_()
        #消息循环显示
        self.root.mainloop()

    def _topmsg_(self):
        topMsg = tk.Label(self.root, text = '美术宝1对1日志查询工具', height = 4, font = ("黑体",22)).pack(side = 'top')

    def _seacherMeun_(self):
        tk.Label(self.root, text = '接口切换：').place(x = 40, y = 120)
        self.vApi = tk.IntVar()
        self.apiLine = tk.Radiobutton(self.root, text = '线上', value = 1, variable = self.vApi).place(x = 120, y = 120)
        self.apiLocal = tk.Radiobutton(self.root, text = '线下', value = 2, variable = self.vApi).place(x = 180, y = 120)
        self.vApi.set(2)

        tk.Label(self.root, text='日志类型：').place(x=260, y=120)
        self.vType = tk.IntVar()
        self.logLocal = tk.Radiobutton(self.root, text = '本地', value = 2, variable = self.vType).place(x = 350, y = 120)
        self.logAgora = tk.Radiobutton(self.root, text = '声网', value = 1, variable = self.vType).place(x=410, y=120)
        self.vType.set(2)

        tk.Label(self.root, text='开始时间：').place(x=40, y=160)
        self.startTime = tk.StringVar(value= time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        sst = tk.Entry(self.root, textvariable = self.startTime)
        sst.place(x = 110, y = 160)
        sst.bind('<Return>', self.setStartTime)
        #tk.Button(self.root, width=5, command=self.setStartTime).place(x = 110, y = 160)
        tk.Label(self.root, text='结束时间：').place(x=300, y=160)
        self.endTime = tk.StringVar(value=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
        est = tk.Entry(self.root, textvariable=self.endTime)
        est.place(x=380, y=160)
        est.bind('<Return>', self.setEndTime)
        #tk.Button(self.root, width=5, command = self.setEndTime).place(x=380, y=160)

        tk.Label(self.root, text='uid：').place(x=40, y=200)
        self.uid = tk.StringVar()
        tk.Entry(self.root, textvariable = self.uid).place(x = 80, y = 200)

        tk.Label(self.root, text='other uid：').place(x=260, y=200)
        self.otheruid = tk.StringVar()
        tk.Entry(self.root, textvariable=self.otheruid).place(x=330, y=200)

        tk.Label(self.root, text='roomid：').place(x=510, y=200)
        self.roomid = tk.StringVar()
        tk.Entry(self.root, textvariable=self.roomid).place(x=560, y=200)

        tk.Label(self.root, text='idfa：').place(x=40, y=240)
        self.idfa = tk.StringVar()
        tk.Entry(self.root, textvariable=self.idfa).place(x=80, y=240)

        tk.Label(self.root, text='build num：').place(x=260, y=240)
        self.buildnum = tk.StringVar()
        tk.Entry(self.root, textvariable=self.buildnum).place(x=330, y=240)

        tk.Label(self.root, text='设备名：').place(x=510, y=240)
        self.device = tk.StringVar()
        tk.Entry(self.root, textvariable=self.device).place(x=560, y=240)

        tk.Label(self.root, text='设备型号：').place(x=40, y=280)
        self.deviceType = tk.StringVar()
        tk.Entry(self.root, textvariable=self.deviceType).place(x=80, y=280)

        tk.Label(self.root, text='系统版本：').place(x=260, y=280)
        self.system = tk.StringVar()
        tk.Entry(self.root, textvariable=self.system).place(x=330, y=280)

        self.searchBtn = tk.Button(self.root, text = '查询', command = self._searchBtn_,
                                width = 10, font = ("黑体",16)).place(x = 760, y = 240)

    def str2Timestamp(self, dateStr):
        d = datetime.datetime.strptime(dateStr, '%Y-%m-%d %H:%M:%S')
        return int(time.mktime(d.timetuple()))

    def setEndTime(self, event):
        c = Calendar((600, 500), 'ur')
        str = c.selection()
        if str is not None:
            self.endTime.set(str)
        self.root.focus_force()
        # setStartTime = lambda: [
        #     self.startTime.set(date)
        #     for date in [Calendar((100, 100), 'ur').selection()]
        #     if date]

    def setStartTime(self, event):
        c = Calendar((500, 500), 'ur')
        str = c.selection()
        if str is not None:
            self.startTime.set(str)
        self.root.focus_force()

    def timestamp2Str(self, tamp):
        localtime = time.localtime(tamp)
        return time.strftime('%Y-%m-%d %H:%M:%S', localtime)

    def _searchBtn_(self):
        '''
        查询数据
        :return:
        '''
        #获取参数
        map = {}
        map['logtype'] = self.vType.get()
        map['uid'] = self.uid.get()
        map['otheruid'] = self.otheruid.get()
        map['idfa'] = self.idfa.get()
        map['build'] = self.buildnum.get()
        map['roomid'] = self.roomid.get()
        map['devices_name'] = self.device.get()
        map['devicetype'] = self.deviceType.get()
        map['sys'] = self.system.get()
        map['starttime'] = self.str2Timestamp(self.startTime.get())
        map['endtime'] = self.str2Timestamp(self.endTime.get())

        if len(self.logInfos):
            self.logInfos.clear()
            self.logInfos = []

        self.logInfos = seacheData(self.vApi.get(), map)
        #处理数据
        #清空数据
        self._clearList_()
        if len(self.logInfos):
            for log in self.logInfos:
                # 添加数据（测试）
                self.listView.insert('', 'end', values=[time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(log.ctime)), log.type, log.build, log.uid, log.roomid, log.logurl])

    def _clearList_(self):
        items = self.listView.get_children()
        for item in items:
            self.listView.delete(item)

    def _resultList_(self):
        vBar = tk.Scrollbar(self.root)
        vBar.pack(side=tk.RIGHT,fill=tk.Y)

        head = ['上传时间', '系统', '版本', 'uid', 'roomid']
        self.listView = ttk.Treeview(self.root,
                                     columns=head,
                                     yscrollcommand=vBar.set,
                                     show='headings',
                                     height = 23,
                                     selectmode = tk.BROWSE)

        self.listView.column('0', width=220, anchor='center')
        self.listView.column('1', width=100, anchor='center')
        self.listView.column('2', width=150, anchor='center')
        self.listView.column('3', width=220, anchor='center')
        self.listView.column('4', width=220, anchor='center')

        self.listView.heading('0', text=head[0])
        self.listView.heading('1', text=head[1])
        self.listView.heading('2', text=head[2])
        self.listView.heading('3', text=head[3])
        self.listView.heading('4', text=head[4])

        vBar.config(command=self.listView.yview)
        self.listView.place(x = 40, y = 330)

    def _itemDoubleClick_(self, event):
        #print('双击监听')
        for index in self.listView.selection():
            i = self.listView.item(index,"values")
            ShowLog(i[5])

    def _doItemClick_(self):
        self.listView.bind('<Double-Button-1>', self._itemDoubleClick_)


